<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/26
 * Time: 15:53
 */

namespace Home\Logic;


use Admin\Logic\MoneyLogLogic;
use Common\Utils\Constants;
use Think\Exception;
use Think\Log;

class CheckInLogLogic
{
    /**
     * 判断用户是否已经签到
     * @param $user_id int 用户id
     * @return bool 是否已经签到
     */
    public function isCheckIn($user_id){
        $map['create_time'] = array('gt',strtotime(date("Y-m-d")));
        $map['user_id'] = $user_id;
        $count = D('CheckInLog')->where($map)->count();
        if($count > 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 用户签到
     * @param $user_id int 用户id
     * @return array 0 已经签到过 1签到成功 2签到失败
     */
    public function checkIn($user_id){
        if($this->isCheckIn($user_id)){
           return array('status'=>0);
        }
        $model = M();
        $model->startTrans();
        try {
            $log['user_id'] = $user_id;
            $log['create_time'] = time();
            $model->table('t_check_in_log')->add($log);
            $config = $model->table('t_config')->where(array('name' => Constants::CONFIG_CHECK_IN_GOLD))->find();
            $money = $config['value'];
            if (is_numeric($money) && $money > 0) {//签到奖励金币数
                $model->table('t_user')->where(array('id' => $user_id))->setInc('gold', $money);
                $currentGold = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
                $moneyLogic = new MoneyLogLogic();
                $remark = '签到获得金币';
                //记录资金流动
                $moneyLogic->saveMoneyLog($money, $currentGold,
                    Constants::MONEY_SOURCE_CHECK_IN,//签到
                    Constants::PUT_TYPE_IN, $remark, $user_id, Constants::MONEY_TYPE_GOLD, $model);
            }
            $model->commit();
            return array('status'=>1,'money'=>$money);
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return array('status'=>2);
        }
    }
}